package com.atguigu.gmall.controller;

import com.alibaba.fastjson.JSON;
import com.atguigu.gmall.Service.OrderInfoService;
import com.atguigu.gmall.constant.MqConst;
import com.atguigu.gmall.entity.OrderInfo;
import com.atguigu.gmall.result.RetVal;
import com.atguigu.gmall.util.AuthContextHolder;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/order")
public class OrderController {

    @Autowired
    private OrderInfoService orderInfoService;


    //返回确认用户的信息，包括地址，商品的信息，总价值等等
    @GetMapping("/confirm")
    public RetVal<Map<String, Object>> confirm(HttpServletRequest request) {
        Map<String, Object> retMap = orderInfoService.confirmOrder(request);
        return RetVal.ok(retMap);
    }

    //点击提交订单时，触发
    @PostMapping("/submitOrder")
    public RetVal submitOrder(@RequestBody OrderInfo orderInfo, HttpServletRequest request) {
        String userId = AuthContextHolder.getUserId(request);
        orderInfo.setUserId(Long.parseLong(userId));
        String tradeNo = request.getParameter("tradeNo");//获取tradeNo 流水号
        if (orderInfoService.checkTradeNo(userId, tradeNo))//检查是否无刷新重复提交
            return RetVal.fail().message("请勿重复提交！");
        //验证库存和价格
        List<String> warningInfoList = orderInfoService.checkStockAndPrice(orderInfo, userId);
        if (warningInfoList.size() > 0) {
            return RetVal.fail().message(StringUtils.join(warningInfoList, ","));
        }
        //确认生成订单，删除流水号
        orderInfoService.deleteTradeNo(userId);
        //保存订单信息
        Long orderId = orderInfoService.saveOrderInfoAndDetail(orderInfo);
        //返回订单的id
        return RetVal.ok(orderId);
    }

    @GetMapping("/getPayOrderInfo/{orderId}")
    public OrderInfo findOrderById(@PathVariable Long orderId) {
        return orderInfoService.findOrderById(orderId);
    }

    @GetMapping("getOrderPageList/{currentPage}/{limit}")
    public IPage<OrderInfo> getOrderPageList(@PathVariable Long currentPage, @PathVariable Long limit, HttpServletRequest request){
        //获取用户id
        String userId = AuthContextHolder.getUserId(request);
        //根据用户id，获取用户所有订单，使用分页
        IPage<OrderInfo> orderInfoPage = new Page<>(currentPage, limit);
        QueryWrapper<OrderInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        return orderInfoService.page(orderInfoPage, queryWrapper);
    }

    //4.拆单接口  参数示例：mapJson [{"wareHouseId":"1","skuIdList":["18","19"]},{"wareHouseId":"2","skuIdList":["30"]}]
    @RequestMapping("/splitOrder")
    public String splitOrder(@RequestParam Long orderId, HttpServletRequest request){
        //获取请求的map，为仓库id对应
        String wareHouseIdSkuIdJson = request.getParameter("wareHouseIdSkuIdMap");
        List<OrderInfo> childOrderList = orderInfoService.splitOrder(orderId,wareHouseIdSkuIdJson);
        //组装子订单数据信息返回给库存系统 库存系统保存到 库存工作单表 库存工作单表明细表中
        List<Map<String, Object>> dataList = new ArrayList<>();
        for (OrderInfo orderInfo : childOrderList) {
            Map<String, Object> map = orderInfoService.assembWareHouseData(orderInfo);
            dataList.add(map);
        }
        return JSON.toJSONString(dataList);

    }

    @PostMapping("saveOrderInfoAndDetail")
    public Long saveOrderInfoAndDetail(@RequestBody OrderInfo orderInfo){
       return orderInfoService.saveOrderInfoAndDetail(orderInfo);
    }

}
